/**
 * @author baz
 */
package lib {
import flash.display.Stage;
import flash.events.KeyboardEvent;

public class KeyboardManager {
    private var stage:Stage;

    public static function set stage(stage:Stage):void {
        KeyboardManager.$.stage = stage;
        KeyboardManager.$.stage.addEventListener(KeyboardEvent.KEY_UP, KeyboardManager.$.upHandler);
        KeyboardManager.$.stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyboardManager.$.downHandler);
    }
    private var keysPressed:Object;

    private static var instance:KeyboardManager;

    public static function get $():KeyboardManager {
        return instance ||= new KeyboardManager();
    }

    public function KeyboardManager() {
        this.keysPressed = new Object();
    }

    /**
     * Is given key pressed?
     * @param keyCode
     * @return
     */
    public function isDown(keyCode:uint):Boolean {
        return Boolean(keyCode in keysPressed);
    }

    private function upHandler(e:KeyboardEvent):void {
        delete keysPressed[e.keyCode];
    }

    private function downHandler(e:KeyboardEvent):void {
        keysPressed[e.keyCode] = true;
    }

    public function kill():void {
        this.stage = null;
        this.keysPressed = new Object();
        stage.removeEventListener(KeyboardEvent.KEY_UP, upHandler);
        stage.removeEventListener(KeyboardEvent.KEY_DOWN, downHandler);
    }
}
}